#!/usr/bin/python
# -*- coding: utf-8 -*-
#创建SocketServerTCP服务器：
import time
import threading  
import time
import serial
import fandCom
class serialThread(threading.Thread):  
    def __init__(self,pqueue,t_name = 'serialThread'):  
        threading.Thread.__init__(self, name=t_name) 
        self.queue = pqueue    #返回动作事件的列队
        self.dev = fandCom.getComPort(True)         #串口端口号
        self.btv = 115200       #串口波特率
        self.t = None           #串口
        self.max_size = 1024
        self.initSerial()
    def initSerial(self):
        print(self.dev,self.btv)
        self.t = serial.Serial(self.dev,self.btv,timeout=1)
        if self.t:
            print(self.t.name)               #串口名
            print(self.t.port)               #串口号
            print(self.t.baudrate)           #波特率
            print(self.t.bytesize)           #字节大小
            print(self.t.parity)             #校验位N－无校验，E－偶校验，O－奇校验
            print(self.t.stopbits)           #停止位
            print(self.t.timeout)            #读超时设置
            print(self.t.writeTimeout)       #写超时
            print(self.t.xonxoff)            #软件流控
            print(self.t.rtscts)             #硬件流控
            print(self.t.dsrdtr)             #硬件流控
            print(self.t.interCharTimeout)   #字符间隔超时
            print('-'*10)
            time.sleep(1)
            self.sendCmd('#')
        # 创建线程，接收串口返回信息
        recive = threading.Thread(target=self.recv_from_serial)
        recive.setDaemon(True)
        recive.start()
    def sendCmd(self,cmd):
        sendstr = cmd
        print(sendstr)
        s = self.t.write(sendstr.encode())
        self.t.flush()
    #https://www.cnblogs.com/engpj/p/16933904.html
    def recv_from_serial(self):
        """
        接收串口返回信息
        """
        serialDelay = 0.001
        while True:
            n = self.t.inWaiting()
            while n<=0:
                time.sleep(serialDelay)
                n = self.t.inWaiting()
            pstr = self.t.read(n)
            print(str(pstr))

    def run(self):
        while True:
            if not self.queue.empty():
                objtmp = self.queue.get()
                self.sendCmd(objtmp.dat)
            else:
                time.sleep(0.001)

#主函数,程序从这里开始运行
def main():
    pass
    
if __name__ == '__main__':
    main()
    # test()


